package com.baihang.platform.shiro;

import java.util.Collection;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.project.ds.config.SystemConfig;

import redis.clients.jedis.Jedis;


public class SystemAuthorizingRealm extends AuthorizingRealm {
	private static Logger logger = LoggerFactory.getLogger(SystemAuthorizingRealm.class);
	private SystemAuthorizingService service;
	private Jedis jedis = RedisKit.getJedis();
	public SystemAuthorizingService getService() {
		return service;
	}

	public void setService(SystemAuthorizingService service) {
		this.service = service;
	}

	

	/**
	 * 身份认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken userToken = (UsernamePasswordToken)token;
		System.err.println("身份认证");
		String userName = userToken.getUsername();
		System.err.println(userName);
		String password=null;
		if(userToken.getPassword().length==0) {//如果使用验证码
			password = "";
		}else {
		    password = String.valueOf(userToken.getPassword());
		}
		System.err.println("password="+password);
		if("1".equals(jedis.hmget("systemConfig","LoginTest").get(0))) {
			User user = new User();
			user.setUserName(userName);
			user.setRealName(userName+"测试帐号");
			user.setUserCode(userName+"身份证");
			user.setType("0");
			//SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, userName);
			if(info !=null) {
				keepOnlyOneUser(userName);
			}
			return info;
		}else {
			Record record = service.getUserRecord(userName,password);
			if(record !=null) {
				User user = new User();
				user.setUserName(record.getStr("D_Tel"));
				user.setRealName(record.getStr("D_Name"));
				user.setUserCode(record.getStr("D_Card"));
				user.setType(String.valueOf(record.getInt("D_Source")));
				//SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
				SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, userName);
				if(info !=null) {
					keepOnlyOneUser(userName);
				}
				return info;
			}
			logger.info("验证失败了");
			return null;						
		}
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 同一帐号，只能有一个在线
	 * @param userName
	 */
	public void keepOnlyOneUser(String userName) {
		 //处理session 将同样的帐号先删除先
       DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
       DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();
       Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();//获取当前已登录的用户session列表
       for(Session session:sessions){
           //清除该用户以前登录时保存的session
       	Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
       	if(obj!=null) {
       		SimplePrincipalCollection spc =(SimplePrincipalCollection)obj;
       		if (spc.getPrimaryPrincipal() != null) {
					User user = (User) spc.getPrimaryPrincipal();// 转成User
					if(user.getUserName().equals(userName)) {
						sessionManager.getSessionDAO().delete(session);//删除
						logger.info("{}被踢下线",userName);
					}
				}
       	}else {
       		continue;
       	}       	
       }
	}

}
